// 作者:wisher
// 时间:2023/6/25
// 说明:微信登录处理

let nextTokenTime = 0
let lastToken = 0
const db = uniCloud.database();
getToken = async () => {
	if (nextTokenTime > new Date().getTime()) return lastToken
	const res = await uniCloud.httpclient.request(
		`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxcf678d102de3f37a&secret=09cd5e6c7e8155b2ee342c023dba6ea3`, {
			method: 'get',
			dataType: 'json', // 指定返回值为json格式，自动进行parse
		})
	let data = res.data
	lastToken = data.access_token
	nextTokenTime = new Date().getTime() + data.expires_in
	return lastToken
}

exports.main = async (event, context) => {
	let res = await uniCloud.httpclient.request(
		`https://api.weixin.qq.com/sns/jscode2session?appid=wxcf678d102de3f37a&secret=09cd5e6c7e8155b2ee342c023dba6ea3&js_code=${event.code}&grant_type=authorization_code`, {
			method: 'get',
			dataType: 'json', // 指定返回值为json格式，自动进行parse
		})
	event.openid = res.data.openid

	const collection = db.collection('users');
	let user = (await collection.where({
		openid: event.openid
	}).get()).data
	let ret = user
	if (user.length == 0) {
		//账号不存在
		ret = (await collection.doc((await collection.add({
			username: event.userInfo.nickName,
			avatarUrl: event.userInfo.avatarUrl,
			phoneNumber: 0,
			openid: event.openid,
			regtime: new Date().getTime()
		})).id).get()).data
	}

	//返回数据给客户端
	return {
		code: 0,
		data: ret[0]
	}
};